# -*- coding: utf-8 -*-
__author__ = 'bobby'

import django_filters
from django.db.models import Q

from .models import InvolverInfo, MigrantsInfo, Party


class InvolverInfoFilter(django_filters.rest_framework.FilterSet):
    time_range = django_filters.DateTimeFromToRangeFilter(method='time_range__filter')
    motion_path__address = django_filters.CharFilter(field_name='motion_path__address', lookup_expr='icontains')

    def time_range__filter(self, queryset, name, value):
        q1 = Q(motion_path__begin_time__range=[value.start, value.stop])
        q2 = Q(motion_path__end_time__range=[value.start, value.stop])
        q3 = ~Q(motion_path__begin_time__lte=value.start) & ~Q(motion_path__end_time__lte=value.start)
        q4 = ~Q(motion_path__begin_time__lte=value.stop) & ~Q(motion_path__end_time__lte=value.stop)
        return queryset.filter(q1 | q2).distinct()

    class Meta:
        model = InvolverInfo
        fields = ['name', 'mobile', 'sex', 'status','delete_flag']


class MigrantsInfoFilter(django_filters.rest_framework.FilterSet):
    time_range = django_filters.DateTimeFromToRangeFilter(method='time_range__filter')

    def time_range__filter(self, queryset, name, value):
        q1 = Q()
        q1.connector = 'OR'
        if value.start and value.stop:
            q1 = Q(arrival_time__range=[value.start, value.stop])
            return queryset.filter(q1)
        return queryset

    class Meta:
        model = MigrantsInfo
        fields = '__all__'


class PartyFilter(django_filters.rest_framework.FilterSet):
    class Meta:
        model = Party
        fields = '__all__'
